package com.hifar.test.test.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hifar.abi.utils.minio.MinioUtils;
import com.hifar.constant.SystemConsts;
import com.hifar.fw.utils.lang.CollectionUtils;
import com.hifar.fw.utils.lang.NumberUtils;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.generate.utils.base.ConstantUtil;
import com.hifar.idm.util.ConvertPdfUtil;
import com.hifar.log.AutoLogUtils;
import com.hifar.plat.AopOption.DictModel;
import com.hifar.plat.baseModal.pojo.BaseOssFiles;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.baseModal.service.IBaseSysDictClassifyService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.plat.user.pojo.BaseOrgUserPlat;
import com.hifar.plat.user.service.IBaseOrgUserService;
import com.hifar.sys.BusiResponse;
import com.hifar.sys.MinioUtil;
import com.hifar.test.entrust.constant.PieceConsts;
import com.hifar.test.entrust.constant.TestConsts;
import com.hifar.test.entrust.pojo.HfEnvEntrust;
import com.hifar.test.entrust.pojo.HfEnvGkEntrust;
import com.hifar.test.entrust.service.IHfEnvGkEntrustService;
import com.hifar.test.report.render.model.HfEnvTaskTestModel;
import com.hifar.test.task.pojo.VO.EquipTestInfoVO;
import com.hifar.test.task.pojo.VO.HfEnvTaskTestVO;
import com.hifar.test.task.service.IHfEnvTaskService;
import com.hifar.test.test.mapper.HfEnvTestMapper;
import com.hifar.test.test.pojo.*;
import com.hifar.test.test.pojo.VO.*;
import com.hifar.test.test.render.HfEnvOriginalRecordRender;
import com.hifar.test.test.service.*;
import com.hifar.utils.FileUtil;
import com.hifar.utils.ToolKit;
import com.tssk.kylx.fw.utils.id.IdUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.awt.*;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 委托试验 服务实现类
 * </p>
 *
 * @author wei
 * @since 2024-12-04 15:51:56
 */
@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class HfEnvTestServiceImpl extends ServiceImpl<HfEnvTestMapper, HfEnvTest> implements IHfEnvTestService {

    @Autowired
    private IBaseOssFilesService baseOssFilesService;
    @Autowired
    private IHfEnvTestExceptionService testExceptionService;

    @Autowired
    private HfEnvOriginalRecordRender originalRecordRender;
    @Autowired
    private IHfEnvTestSensorService testSensorService;

    @Autowired
    private IHfEnvTestPersonService testPersonService;

    @Autowired
    private IHfEnvTestPieceService testPieceService;

    @Autowired
    private IHfEnvTaskTestRelationService taskTestRelationService;

    @Autowired
    private IBaseOrgUserService baseOrgUserService;

    @Autowired
    private IHfEnvTaskService taskService;

    @Autowired
    private IHfEnvGkEntrustService gkEntrustService;

    @Autowired
    private IBaseSysDictClassifyService sysDictClassifyService;


    @Autowired
    private AutoLogUtils autoLogUtils;


    @Override
    public Page<HfEnvTestVO> pageVO(Page<HfEnvTestVO> page, QueryWrapper<HfEnvTestVO> queryWrapper) {
        Page<HfEnvTestVO> pageVoData = baseMapper.pageVO(page, queryWrapper);
        List<HfEnvTestVO> records = pageVoData.getRecords();
        if (records.isEmpty()) {
            return pageVoData;
        }

        for (HfEnvTestVO hfEnvTestVO : records) {
            String id = hfEnvTestVO.getId();
            String pdfPathXh = hfEnvTestVO.getPdfPathXh();
            String docxPathXh = hfEnvTestVO.getDocxPathXh();
            Integer secretLevel = hfEnvTestVO.getSecretLevel();
            List<HfEnvGkEntrust> gkEntrustList = baseMapper.selectGkEntrustByTestId(id);
            String entrustCusts = gkEntrustList.stream()
                    .map(HfEnvGkEntrust::getEntrustCust)
                    .distinct()
                    .collect(Collectors.joining(","));
            hfEnvTestVO.setEntrustCust(entrustCusts);
            hfEnvTestVO.setEntrustList(gkEntrustList);
            Integer testExceptionNum = testExceptionService.queryTestExceptionNum(id);
            hfEnvTestVO.setExceptionNum(testExceptionNum);
            if (StringUtils.isNotBlank(pdfPathXh)) {
                hfEnvTestVO.setPdfPathXh(MinioUtil.getFullFilePaths(MinioUtil.PRE_DEFAULT, pdfPathXh, secretLevel));
            }
            if (StringUtils.isNotBlank(docxPathXh)) {
                hfEnvTestVO.setDocxPathXh(MinioUtil.getFullFilePaths(MinioUtil.PRE_DEFAULT, docxPathXh, secretLevel));
            }
        }
        return pageVoData;
    }


    @Override
    public void start(HfEnvTestStartVO testStartVO) {
        String id = testStartVO.getId();
        Date realStartTime = testStartVO.getRealStartTime();
        String remarks = testStartVO.getRemarks();
        HfEnvTest envTest = getById(id);
        Assert.notNull(envTest, "数据不存在!");
        String testCode = envTest.getTestCode();
        String status = StringUtils.trimNull(envTest.getStatus(), "1");
        Assert.isTrue(Objects.equals(TestConsts.TEST_STATUS_WKS, status), "试验已开始,不能再次开始!");
        autoLogUtils.modifyLog("环境试验-任务执行", String.format("执行单【%s】开始", testCode));
        envTest.setStatus(TestConsts.TEST_STATUS_RUN);
        envTest.setRealStartTime(realStartTime);
        envTest.setRemarks(remarks);
        this.updateById(envTest);

        taskService.refreshTaskStatus(id);
    }

    @Override
    public void forceEnd(HfEnvTestForceEndVO testForceEndVO) {
        String id = testForceEndVO.getId();
        Date realEndTime = testForceEndVO.getRealEndTime();
        String remarks = testForceEndVO.getRemarks();

        List<BaseOssFiles> forceEndFileList = Optional.ofNullable(testForceEndVO.getFiles()).orElse(new ArrayList<>());

        HfEnvTest envTest = getById(id);
        String status = envTest.getStatus();
        Assert.notNull(envTest, "数据不存在!");
        Assert.isTrue(!Objects.equals(TestConsts.TEST_STATUS_FINISH, status), "试验已完成,不能中断!");
        Assert.isTrue(!Objects.equals(TestConsts.TEST_STATUS_STOP, status), "试验已中断,不能再次中断!");
        //  修改状态
        envTest.setRealEndTime(realEndTime);
        envTest.setRemarks(remarks);
        envTest.setStatus(TestConsts.TEST_STATUS_STOP);
        this.updateById(envTest);

        for (BaseOssFiles ossFiles : forceEndFileList) {
            ossFiles.setRefType(TestConsts.TEST_REF_TYPE_FORCE_END);
            ossFiles.setRefId(id);
        }
        UpdateWrapper<BaseOssFiles> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(BaseOssFiles::getRefId, null)
                .eq(BaseOssFiles::getRefId, id)
                .eq(BaseOssFiles::getRefType
                        , TestConsts.TEST_REF_TYPE_FORCE_END);
        baseOssFilesService.update(updateWrapper);
        baseOssFilesService.updateBatchById(forceEndFileList);

        taskService.refreshTaskStatus(id);

        String testCode = envTest.getTestCode();
        autoLogUtils.modifyLog("环境试验-任务执行", String.format("执行单【%s】终止", testCode));

    }

    @Override
    public void finish(HfEnvTestFinishVO testFinishVO) {
        String id = testFinishVO.getId();
        Date realEndTime = testFinishVO.getRealEndTime();
        String finishUserId = testFinishVO.getFinishUserId();
        String finishUserName = testFinishVO.getFinishUserName();
        HfEnvTest envTest = getById(id);
        Assert.notNull(envTest, "数据不存在!");
        String status = envTest.getStatus();
        Date realStartTime = envTest.getRealStartTime();
        String izSaveData = envTest.getIzSaveData();

        Assert.isTrue(!Objects.equals(status, TestConsts.TEST_STATUS_WKS), "试验未开始,不能进行完成!");
        Assert.isTrue(Objects.equals(izSaveData, SystemConsts.YES), "试验数据未填写,不能进行完成!");
        Assert.isTrue(realStartTime.before(realEndTime), "结束时间不能小于开始时间!");


        envTest.setRealEndTime(realEndTime);
        envTest.setRealUseTime(realEndTime.getTime() - realStartTime.getTime());
        envTest.setStatus(TestConsts.TEST_STATUS_FINISH);
        envTest.setFinishUserId(finishUserId);
        envTest.setFinishUserName(finishUserName);
        this.updateById(envTest);
        taskService.refreshTaskStatus(id);

        this.generateProcessRecord(id);
        String testCode = envTest.getTestCode();
        autoLogUtils.modifyLog("环境试验-任务执行", String.format("执行单【%s】完成", testCode));
    }

    @Override
    public void revoke(HfEnvTestRevokeVO testRevokeVO) {
        String id = testRevokeVO.getId();
        HfEnvTest envTest = getById(id);
        Assert.notNull(envTest, "数据不存在!");
        String status = envTest.getStatus();
        Assert.isTrue(Objects.equals(status, TestConsts.TEST_STATUS_WKS), "试验已开始,无法撤销!");
        envTest.setStatus(TestConsts.TEST_STATUS_REVOKE);
        this.updateById(envTest);

        taskService.refreshTaskStatus(id);

        String testCode = envTest.getTestCode();
        autoLogUtils.modifyLog("环境试验-任务执行", String.format("执行单【%s】撤销", testCode));
    }

    @Override
    public void saveTestData(HfEnvTestDataVO testData) {
        String id = testData.getId();
        HfEnvTest envTest = this.getById(id);
        Assert.notNull(envTest, "数据不存在!");
        BeanUtils.copyProperties(testData, envTest);
//        envTest.setStatus(TestConsts.TEST_STATUS_ING);
        envTest.setIzSaveData(SystemConsts.YES);
        this.updateById(envTest);
        String testCode = envTest.getTestCode();

        List<BaseOssFiles> testFileList = Optional.ofNullable(testData.getTestFileList()).orElse(new ArrayList<>(0));
        List<BaseOssFiles> testImageList = Optional.ofNullable(testData.getTestImageList()).orElse(new ArrayList<>(0));
        List<BaseOssFiles> swingStatusList = Optional.ofNullable(testData.getSwingStatusList()).orElse(new ArrayList<>(0));
        List<BaseOssFiles> testChartList = Optional.ofNullable(testData.getTestChartList()).orElse(new ArrayList<>(0));
        List<BaseOssFiles> testCurveList = Optional.ofNullable(testData.getTestCurveList()).orElse(new ArrayList<>(0));
        for (BaseOssFiles baseOssFiles : testChartList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType(TestConsts.TEST_REF_TYPE_CHART);
        }

        for (BaseOssFiles baseOssFiles : testImageList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType(TestConsts.TEST_REF_TYPE_IMAGE);
        }
        for (BaseOssFiles baseOssFiles : testFileList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType(TestConsts.TEST_REF_TYPE_FILE);
        }

        for (BaseOssFiles baseOssFiles : testCurveList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType(TestConsts.TEST_REF_TYPE_CURVE);
        }

        UpdateWrapper<BaseOssFiles> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(BaseOssFiles::getRefId, null)
                .eq(BaseOssFiles::getRefId, id)
                .in(BaseOssFiles::getRefType
                        , TestConsts.TEST_REF_TYPE_IMAGE
                        , TestConsts.TEST_REF_TYPE_FILE
                        , TestConsts.TEST_REF_TYPE_CHART
                        , TestConsts.TEST_REF_TYPE_CURVE);
        baseOssFilesService.update(updateWrapper);
        baseOssFilesService.updateBatchById(testImageList);
        baseOssFilesService.updateBatchById(testFileList);
        baseOssFilesService.updateBatchById(swingStatusList);
        baseOssFilesService.updateBatchById(testChartList);
        baseOssFilesService.updateBatchById(testCurveList);
        testSensorService.removeByTestId(id);
        List<HfEnvTestSensor> sensorList = Optional.ofNullable(testData.getSensorList()).orElse(new ArrayList<>(0));

        TestUserVO testUserVO = Optional.ofNullable(testData.getTestUser()).orElse(new TestUserVO());

        for (int i = 0; i < sensorList.size(); i++) {
            HfEnvTestSensor hfEnvTestSensor = sensorList.get(i);
            hfEnvTestSensor.setId(null);
            hfEnvTestSensor.setTestId(id);
            hfEnvTestSensor.setRowSort(i);
        }
        testSensorService.saveBatch(sensorList);

        String testUserIds = testUserVO.getId();
        List<String> testUserIdList = CollectionUtils.valueOfList(testUserIds);
        List<HfEnvTestPerson> testUserList = new ArrayList<>();
        List<BaseOrgUserPlat> testBaseUserList = new ArrayList<>();
        if (!testUserIdList.isEmpty()) {
            testBaseUserList = baseOrgUserService.listByIds(testUserIdList);
        }
        for (int i = 0; i < testBaseUserList.size(); i++) {
            BaseOrgUserPlat baseOrgUserPlat = testBaseUserList.get(i);
            String userId = baseOrgUserPlat.getId();
            String userName = baseOrgUserPlat.getIdName();
            HfEnvTestPerson hfEnvTestPerson = new HfEnvTestPerson();
            hfEnvTestPerson.setUserId(userId);
            hfEnvTestPerson.setUserName(userName);
            hfEnvTestPerson.setTestId(id);
            hfEnvTestPerson.setRowSort(i + 1);
            testUserList.add(hfEnvTestPerson);
        }
        testPersonService.saveTestUserList(id, testUserList);

        List<HfEnvTestPiece> testPieceList = Optional.ofNullable(testData.getTestPieceInfo())
                .orElse(new ArrayList<>());


        for (int i = 0; i < testPieceList.size(); i++) {
            HfEnvTestPiece hfEnvTestPiece = testPieceList.get(i);
            hfEnvTestPiece.setId(null);
            hfEnvTestPiece.setStatus(PieceConsts.PIECE_STATUS_CG);
            hfEnvTestPiece.setTestId(id);
            hfEnvTestPiece.setRowSort(i + 1);
        }
        testPieceService.removeByTestId(id);
        testPieceService.saveBatch(testPieceList);

        autoLogUtils.modifyLog("环境试验-任务执行", String.format("执行单【%s】保存试验数据", testCode));
    }

    @Override
    public HfEnvTestDataVO queryTestData(String id) {
        HfEnvTest envTest = getById(id);
        HfEnvTestDataVO testDataVO = new HfEnvTestDataVO();
        testDataVO.setId(id);
        BeanUtils.copyProperties(envTest, testDataVO);
        List<BaseOssFiles> testFileList = MinioUtil.listByRefId(id, TestConsts.TEST_REF_TYPE_FILE);
        List<BaseOssFiles> testImageList = MinioUtil.listByRefId(id, TestConsts.TEST_REF_TYPE_IMAGE);
        List<BaseOssFiles> testChartList = MinioUtil.listByRefId(id, TestConsts.TEST_REF_TYPE_CHART);
        List<BaseOssFiles> testCurveList = MinioUtil.listByRefId(id, TestConsts.TEST_REF_TYPE_CURVE);

        List<HfEnvTestSensor> testSensorList = testSensorService.listByTestId(id);

        List<HfEnvTestPiece> testPieceList = testPieceService.listPieceByTestId(id);


        testDataVO.setTestFileList(testFileList);
        testDataVO.setTestImageList(testImageList);
        testDataVO.setTestChartList(testChartList);
        testDataVO.setTestCurveList(testCurveList);
        testDataVO.setSensorList(testSensorList);
        testDataVO.setTestPieceInfo(testPieceList);
        List<HfEnvTestPerson> testUserList = testPersonService.listTestTestUser(id);
        TestUserVO testUserVO = new TestUserVO();
        List<String> userIdList = new ArrayList<>();
        List<String> userNameList = new ArrayList<>();
        for (HfEnvTestPerson hfEnvTestPerson : testUserList) {
            userIdList.add(hfEnvTestPerson.getUserId());
            userNameList.add(hfEnvTestPerson.getUserName());
        }
        testUserVO.setId(String.join(",", userIdList));
        testUserVO.setName(String.join(",", userNameList));
        testDataVO.setTestUser(testUserVO);
        return testDataVO;
    }

    @Override
    public void saveTestChart(HfEnvTestChartVO testChartVO) {
        String id = testChartVO.getId();
        HfEnvTest hfEnvTest = getById(id);
        Assert.notNull(hfEnvTest, "试验数据不存在!");
        List<BaseOssFiles> testChartList = testChartVO.getTestChartList();
        for (BaseOssFiles baseOssFiles : testChartList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType(TestConsts.TEST_REF_TYPE_CHART);
        }
        UpdateWrapper<BaseOssFiles> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(BaseOssFiles::getRefId, null)
                .eq(BaseOssFiles::getRefId, id)
                .eq(BaseOssFiles::getRefType, TestConsts.TEST_REF_TYPE_CHART);
        baseOssFilesService.update(updateWrapper);
        baseOssFilesService.updateBatchById(testChartList);
        String testCode = hfEnvTest.getTestCode();
        autoLogUtils.modifyLog("环境试验-任务执行", String.format("执行单【%s】保存试验图谱", testCode));
    }

    @Override
    public HfEnvTestChartVO queryTestChart(String id) {
        HfEnvTestChartVO testChartVO = new HfEnvTestChartVO();
        testChartVO.setId(id);
        List<BaseOssFiles> testChartList = MinioUtil.listByRefId(id, TestConsts.TEST_REF_TYPE_CHART);
        testChartVO.setTestChartList(testChartList);
        return testChartVO;
    }

    @Override
    public Page<HfEnvTest> testListPage(Page<HfEnvTest> page, QueryWrapper<HfEnvTest> queryWrapper) {
        return page(page, queryWrapper);
    }

    @Override
    public List<EquipTestInfoVO> queryAllTestInfo(Date startTime, Date endTime) {
        QueryWrapper<HfEnvTest> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(startTime)) {
            queryWrapper
                    .lambda()
                    .gt(HfEnvTest::getRealStartTime, startTime);
        }
        if (Objects.nonNull(endTime)) {
            queryWrapper
                    .lambda()
                    .lt(HfEnvTest::getRealEndTime, endTime);
        }
        return baseMapper.selectTestInfo(queryWrapper);
    }


    @Override
    public List<EquipTestInfoVO> listRunTest(List<String> equipIdList, Date startTime, Date endTime) {
        if (equipIdList.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<HfEnvTest> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .in(HfEnvTest::getEquipId, equipIdList)
                .in(HfEnvTest::getStatus
                        , TestConsts.TEST_STATUS_WKS, TestConsts.TEST_STATUS_RUN, TestConsts.TEST_STATUS_ING)
                .gt(Objects.nonNull(startTime), HfEnvTest::getPredictStartTime, startTime)
                .lt(Objects.nonNull(endTime), HfEnvTest::getPredictEndTime, endTime)
                .orderByAsc(HfEnvTest::getRealStartTime, HfEnvTest::getPredictStartTime, HfEnvTest::getPredictEndTime);
        List<HfEnvTest> testList = this.list(queryWrapper);
        List<EquipTestInfoVO> testInfoVoList = testList.stream()
                .map(item -> {
                    EquipTestInfoVO equipTestInfoVO = new EquipTestInfoVO();
                    String status = item.getStatus();
                    Date predictStartTime = item.getPredictStartTime();
                    Date predictEndTime = item.getPredictEndTime();
                    Date realStartTime = item.getRealStartTime();
                    Long predictUseTime = item.getPredictUseTime();
                    String testId = item.getId();

                    List<HfEnvTaskTestRelation> taskTestRelationList = taskTestRelationService.lambdaQuery()
                            .select(HfEnvTaskTestRelation::getGkEntrustId)
                            .eq(HfEnvTaskTestRelation::getTestId, testId)
                            .list();
                    List<String> gkEntrustIdList = taskTestRelationList.stream()
                            .map(HfEnvTaskTestRelation::getGkEntrustId)
                            .collect(Collectors.toList());

                    List<HfEnvGkEntrust> gkEntrustList = gkEntrustService.listByIds(gkEntrustIdList);
                    List<String> entrustCodeList = new ArrayList<>();
                    List<String> entrustCustList = new ArrayList<>();
                    for (HfEnvGkEntrust hfEnvGkEntrust : gkEntrustList) {
                        entrustCodeList.add(hfEnvGkEntrust.getEntrustCode());
                        entrustCustList.add(hfEnvGkEntrust.getEntrustCust());
                    }

                    equipTestInfoVO.setEntrustCode(String.join(",", entrustCodeList));
                    equipTestInfoVO.setEntrustCust(String.join(",", entrustCustList));

                    Date showStartTime = null;
                    Date showEndTime = null;
                    String typeFlag = TestConsts.TYPE_FLAG_NOT_START;
                    if (Objects.equals(TestConsts.TEST_STATUS_WKS, status)) {
                        showStartTime = Objects.nonNull(startTime) ? startTime.before(predictStartTime)
                                ? predictStartTime : endTime : predictStartTime;
                        showEndTime = Objects.nonNull(endTime) ? endTime.before(predictEndTime)
                                ? endTime : predictEndTime : predictEndTime;

                        typeFlag = TestConsts.TYPE_FLAG_NOT_START;
                        if (predictStartTime.before(new Date())) {
                            typeFlag = TestConsts.TYPE_FLAG_TIMEOUT;
                        }
                    } else {
                        typeFlag = TestConsts.TYPE_FLAG_RUNNING;
                        showStartTime = Objects.nonNull(startTime) ? startTime.before(realStartTime)
                                ? realStartTime : endTime : realStartTime;
                        Date predictRealEndTime = new Date(realStartTime.getTime() + predictUseTime);
                        showEndTime = Objects.nonNull(endTime) ? endTime.before(predictRealEndTime)
                                ? endTime : predictRealEndTime : predictRealEndTime;
                    }
                    BeanUtils.copyProperties(item, equipTestInfoVO);
                    equipTestInfoVO.setTypeFlag(typeFlag);
                    equipTestInfoVO.setShowStartTime(showStartTime);
                    equipTestInfoVO.setShowEndTime(showEndTime);
                    return equipTestInfoVO;
                }).collect(Collectors.toList());
        return testInfoVoList;
    }


    @Override
    public void generateProcessRecord(String id) {
        originalRecordRender.renderReport(id);
    }

    @Override
    public void replaceTestReport(String id, String fileId) {
        BaseOssFiles baseOssFile = baseOssFilesService.getById(fileId);
        Assert.notNull(baseOssFile, "附件不存在!");
        HfEnvTest hfEnvTest = this.getById(id);
        Assert.notNull(hfEnvTest, "数据不存在!");

        String wordFilePath = baseOssFile.getFilePath();
        String bucketPre = baseOssFile.getBucketPre();
        String tempWordPath = FileUtil.getTempPath() + File.separator + IdUtils.uuid32() + ".docx";

        String docxObjectName = "hifar/idm/" + id + "Original.docx";
        String pdfObjectName = "hifar/idm/" + id + "Original.pdf";

        String pdfPath = null;
        try {
            MinioUtils.downloadFileToLocal(bucketPre, wordFilePath, tempWordPath);
            MinioUtils.uploadFileToMinioByStream(ConstantUtil.MINIO_BUCKET_PUBLIC, docxObjectName, new File(tempWordPath));
            pdfPath = ConvertPdfUtil.wordToPdf(tempWordPath);
            MinioUtils.uploadLocalFileToMinio(ConstantUtil.MINIO_BUCKET_PUBLIC, pdfObjectName, pdfPath, "application/pdf");
            UpdateWrapper<HfEnvTest> testUpdateWrapper = new UpdateWrapper<>();
            testUpdateWrapper.lambda()
                    .set(HfEnvTest::getDocxPathXh, docxObjectName)
                    .set(HfEnvTest::getPdfPathXh, pdfObjectName)
                    .eq(HfEnvTest::getId, id);
            this.update(testUpdateWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            File tempWordFile = new File(tempWordPath);
            if (tempWordFile.exists()) {
                tempWordFile.delete();
            }
            if (Objects.nonNull(pdfPath)) {
                File tempPdfFile = new File(pdfPath);
                if (tempPdfFile.exists()) {
                    tempPdfFile.delete();
                }
            }
        }
    }


    @Override
    public void delTestReport(String id) {
        HfEnvTest hfEnvTest = this.getById(id);
        Assert.notNull(hfEnvTest, "试验数据不存在!");
        UpdateWrapper<HfEnvTest> testUpdateWrapper = new UpdateWrapper<>();
        testUpdateWrapper.lambda()
                .set(HfEnvTest::getPdfPathXh, null)
                .set(HfEnvTest::getDocxPathXh, null)
                .eq(HfEnvTest::getId, id);
        this.update(testUpdateWrapper);
    }


    @Override
    public List<HfEnvEntrustTestVO> testListByEntrustId(String entrustId) {
        List<HfEnvEntrustTestVO> testVOList = baseMapper.selectEntrustTestVOByEntrustId(entrustId);
        if (testVOList.isEmpty()) {
            return testVOList;
        }
        List<String> testIdList = testVOList.stream()
                .map(HfEnvEntrustTestVO::getId)
                .collect(Collectors.toList());

        Map<String, Integer> chartNumMap = baseOssFilesService.queryFileNum(testIdList, TestConsts.TEST_REF_TYPE_CHART);
        Map<String, Integer> fileNumMap = baseOssFilesService.queryFileNum(testIdList, TestConsts.TEST_REF_TYPE_FILE);
        Map<String, Integer> curveNumMap = baseOssFilesService.queryFileNum(testIdList, TestConsts.TEST_REF_TYPE_CURVE);

        for (HfEnvEntrustTestVO hfEnvEntrustTestVO : testVOList) {
            String id = hfEnvEntrustTestVO.getId();

            Integer chartNum = chartNumMap.getOrDefault(id, 0);
            Integer fileNum = fileNumMap.getOrDefault(id, 0);
            Integer curveNum = curveNumMap.getOrDefault(id, 0);

            hfEnvEntrustTestVO.setCurveImgNum(curveNum);
            hfEnvEntrustTestVO.setChartImgNum(chartNum);
            hfEnvEntrustTestVO.setFileNum(fileNum);

            int sensorNum = testSensorService.lambdaQuery()
                    .eq(HfEnvTestSensor::getTestId, id)
                    .count();
            int testPersonNum = testPersonService.lambdaQuery()
                    .eq(HfEnvTestPerson::getTestId, id)
                    .count();
            hfEnvEntrustTestVO.setSensorNum(sensorNum);
            hfEnvEntrustTestVO.setTestPersonNum(testPersonNum);
            Integer secretLevel = hfEnvEntrustTestVO.getSecretLevel();
            String pdfPathXh = hfEnvEntrustTestVO.getPdfPathXh();
            String docxPathXh = hfEnvEntrustTestVO.getDocxPathXh();
            if (StringUtils.isNotBlank(pdfPathXh)) {
                hfEnvEntrustTestVO.setPdfPathXh(MinioUtil.getFullFilePaths(MinioUtil.PRE_DEFAULT, pdfPathXh, secretLevel));
            }
            if (StringUtils.isNotBlank(docxPathXh)) {
                hfEnvEntrustTestVO.setDocxPathXh(MinioUtil.getFullFilePaths(MinioUtil.PRE_DEFAULT, docxPathXh, secretLevel));
            }
        }
        return testVOList;
    }

    @Override
    public List<HfEnvEntrustTestVO> testListByTaskId(String taskId) {
        List<HfEnvEntrustTestVO> testVOList = baseMapper.selectEntrustTestVOByTaskId(taskId);
        if (testVOList.isEmpty()) {
            return testVOList;
        }
        List<String> testIdList = testVOList.stream()
                .map(HfEnvEntrustTestVO::getId)
                .collect(Collectors.toList());

        Map<String, Integer> chartNumMap = baseOssFilesService.queryFileNum(testIdList, TestConsts.TEST_REF_TYPE_CHART);
        Map<String, Integer> fileNumMap = baseOssFilesService.queryFileNum(testIdList, TestConsts.TEST_REF_TYPE_FILE);
        Map<String, Integer> imageNumMap = baseOssFilesService.queryFileNum(testIdList, TestConsts.TEST_REF_TYPE_IMAGE);
        Map<String, Integer> curveNumMap = baseOssFilesService.queryFileNum(testIdList, TestConsts.TEST_REF_TYPE_CURVE);


        for (HfEnvEntrustTestVO hfEnvEntrustTestVO : testVOList) {
            String id = hfEnvEntrustTestVO.getId();

            Integer chartNum = chartNumMap.getOrDefault(id, 0);
            Integer fileNum = fileNumMap.getOrDefault(id, 0);
            Integer imageNum = imageNumMap.getOrDefault(id, 0);
            Integer curveNum = curveNumMap.getOrDefault(id, 0);

            hfEnvEntrustTestVO.setCurveImgNum(curveNum);
            hfEnvEntrustTestVO.setChartImgNum(chartNum);
            hfEnvEntrustTestVO.setFileNum(fileNum);

            QueryWrapper<HfEnvTestSensor> testSensorQueryWrapper = new QueryWrapper<>();
            testSensorQueryWrapper.lambda()
                    .eq(HfEnvTestSensor::getTestId, id);
            int sensorNum = testSensorService.count(testSensorQueryWrapper);
            hfEnvEntrustTestVO.setSensorNum(sensorNum);

            List<HfEnvTestPerson> testPersonList = testPersonService.lambdaQuery()
                    .eq(HfEnvTestPerson::getTestId, id)
                    .orderByAsc(HfEnvTestPerson::getRowSort)
                    .list();
            hfEnvEntrustTestVO.setTestPersonNum(testPersonList.size());
            String testPersonUserName = testPersonList.stream()
                    .map(HfEnvTestPerson::getUserName)
                    .collect(Collectors.joining(","));

            hfEnvEntrustTestVO.setTestPersonUserName(testPersonUserName);


            Integer secretLevel = hfEnvEntrustTestVO.getSecretLevel();
            String pdfPathXh = hfEnvEntrustTestVO.getPdfPathXh();
            String docxPathXh = hfEnvEntrustTestVO.getDocxPathXh();
            if (StringUtils.isNotBlank(pdfPathXh)) {
                hfEnvEntrustTestVO.setPdfPathXh(MinioUtil.getFullFilePaths(MinioUtil.PRE_DEFAULT, pdfPathXh, secretLevel));
            }
            if (StringUtils.isNotBlank(docxPathXh)) {
                hfEnvEntrustTestVO.setDocxPathXh(MinioUtil.getFullFilePaths(MinioUtil.PRE_DEFAULT, docxPathXh, secretLevel));
            }
        }
        return testVOList;
    }

    @Override
    public void saveCurve(HfEnvSaveCurveVO saveCurveVO) {
        String testId = saveCurveVO.getTestId();
        String fileId = saveCurveVO.getFileId();
        HfEnvTest hfEnvTest = getById(testId);
        Assert.notNull(hfEnvTest, "数据不存在!");
        BaseOssFiles baseOssFiles = baseOssFilesService.getById(fileId);
        baseOssFiles.setRefType(TestConsts.TEST_REF_TYPE_CURVE);
        baseOssFiles.setRefId(testId);
        baseOssFilesService.updateById(baseOssFiles);
    }


    @Override
    public List<HfEnvTaskTestVO> reportListVoByTaskId(String taskId) {
        return baseMapper.reportListVoByTaskId(taskId, new ArrayList<>(0));
    }

    @Override
    public List<HfEnvTaskTestModel> listRenderModelByIds(List<String> testIdList) {
        return baseMapper.listRenderModelByIds(testIdList);
    }

    @Override
    public HfEnvTestForceEndVO queryForceEndById(String id) {
        HfEnvTest hfEnvTest = getById(id);
        Assert.notNull(hfEnvTest, "数据不存在!");
        HfEnvTestForceEndVO forceEndVO = new HfEnvTestForceEndVO();
        BeanUtils.copyProperties(hfEnvTest, forceEndVO);
        List<BaseOssFiles> forceEndList = MinioUtil.listByRefId(id, TestConsts.TEST_REF_TYPE_FORCE_END);
        forceEndVO.setFiles(forceEndList);
        return forceEndVO;
    }

    @Override
    public BusiResponse exportExcel(QueryWrapper<HfEnvTestVO> queryWrapper) {
        BusiResponse response = new BusiResponse();
        List<HfEnvTestExportVO> dataList = baseMapper.listExportVO(queryWrapper);
        Set<Integer> secretLevelSet = new HashSet<>();
        for (HfEnvTestExportVO item : dataList) {
            Integer testExceptionNum = testExceptionService.queryTestExceptionNum(item.getId());
//            Long predictUseTime = item.getPredictUseTime();
            Date predictStartTime = item.getPredictStartTime();
            Date predictEndTime = item.getPredictEndTime();
            BigDecimal predictUseHourTime = ToolKit.diffDateHour(predictStartTime, predictEndTime, 2);
            item.setPredictUseTimeText(predictUseHourTime.toPlainString());
            item.setExceptionNum(testExceptionNum);
            String status = item.getStatus();
            secretLevelSet.add(NumberUtils.parseInt(item.getSecretLevel()));
            String statusText = null;
            if (Objects.equals(TestConsts.TEST_STATUS_WKS, status)) {
                statusText = "未开始";
            } else if (Objects.equals(TestConsts.TEST_STATUS_REVOKE, status)) {
                statusText = "撤销";
            } else if (Objects.equals(TestConsts.TEST_STATUS_RUN, status)) {
                statusText = "运行中";
            } else if (Objects.equals(TestConsts.TEST_STATUS_ING, status)) {
                statusText = "运行中";
            } else if (Objects.equals(TestConsts.TEST_STATUS_FINISH, status)) {
                statusText = "完成";
            } else if (Objects.equals(TestConsts.TEST_STATUS_STOP, status)) {
                statusText = "中断";
            } else if (Objects.equals(TestConsts.TEST_STATUS_MOVE_OUT, status)) {
                statusText = "已移出";
            }
            item.setStatusText(statusText);
        }
        Integer maxSecretLve = secretLevelSet.stream().max(Integer::compareTo).orElse(0);
        Map<String, Object> extMap = new HashMap<>();
        extMap.put("secretLve", maxSecretLve);
        List<DictModel> dataSecretList = sysDictClassifyService.queryDictItemsByCode("hf_sys_datasecret");
        Map<String, String> dataSecretMap = dataSecretList.stream()
                .collect(Collectors.toMap(
                        item -> item.getValue(),
                        item -> item.getText(),
                        (o1, o2) -> o1
                ));
        String secretLevelText = dataSecretMap.get(com.hifar.fw.utils.lang.StringUtils.trimNull(maxSecretLve));
        extMap.put("secretLevelText", secretLevelText);
        response.setExt(extMap);

        ExcelTemplateUtil.exportExcelNoTitle(response, dataList, HfEnvTestExportVO.class, "试验查询");
        autoLogUtils.modifyLog("环境试验-试验查询", "试验查询列表导出");
        return response;
    }


    @Override
    public List<HfEnvTest> listByGkEntrustId(String gkEntrustId) {
        List<HfEnvTaskTestRelation> taskTestRelationList = taskTestRelationService.lambdaQuery()
                .eq(HfEnvTaskTestRelation::getGkEntrustId, gkEntrustId)
                .list();
        if (taskTestRelationList.isEmpty()) {
            return new ArrayList<>();
        }

        List<String> testIdList = taskTestRelationList.stream()
                .map(HfEnvTaskTestRelation::getTestId)
                .collect(Collectors.toList());
        return this.listByIds(testIdList);
    }
}
